package sealte.hvpms.servlet.vp;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sealte.hvpms.dao.RuleDAO;
import sealte.hvpms.dao.impl.PollDAOImpl;
import sealte.hvpms.dao.impl.RuleDAOImpl;
import sealte.hvpms.pojo.RuleLocks;
import sealte.hvpms.pojo.UserCreate;
import sealte.hvpms.util.HVPMSTools;

public class ExportVoterInfo extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssZ");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control","no-cache"); 
		response.reset();
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename="+sdf.format(new Date())+".xls");
		UserCreate uc = (UserCreate)request.getSession().getAttribute("UserCreate");
		if(uc!=null){
			String fid_str = request.getParameter("fid");
			String sid_str = request.getParameter("sid");
			if(fid_str!=null&&sid_str!=null&&!fid_str.equals("")&&!sid_str.equals("")){
				int fid = Integer.parseInt(fid_str);
				int sid = Integer.parseInt(sid_str);
				List<RuleLocks> all = null;
				RuleDAO rb = new RuleDAOImpl();
				String[] tableHead = new String[3];
				tableHead[0] = (new PollDAOImpl()).getNameByID(fid);
				tableHead[1] = "序号";
				if(sid==3){
					tableHead[2] = "邮箱";
					all = rb.getAllEmail(fid);
				}else if(sid==5){
					tableHead[2] = "身份证号";
					all = rb.getAllIDCard(fid);
				}
				boolean flag = HVPMSTools.exportExcel(all, tableHead, response.getOutputStream());
				if(!flag){
					response.setContentType("text/html");
					response.getWriter().println("导出Excel出错，请联系开发者"); 
				}
			}else{
				response.setContentType("text/html");
				response.getWriter().println("系统出错，请联系开发者");
			}
		}else{
			response.setContentType("text/html");
			response.getWriter().println("谢绝跨路径访问");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
